package de.tum.in.eist.poll.server;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.client.Window;

import de.tum.in.eist.poll.pub.shared.Feedback;
import de.tum.in.eist.poll.pub.shared.FeedbackExtended;
import de.tum.in.eist.poll.pub.shared.Lecture;
import de.tum.in.eist.poll.pub.shared.Student;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Storage {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void submitFeedback(FeedbackExtended fb) throws IOException {
		int q1 = fb.q1;
		String q2 = fb.q2;
		String q3 = fb.q3;
		Student curUser = fb.getStudent();
		Lecture curLecture = fb.getLecture();
		if (!feedbackExists(curLecture, curUser)) {
			Key id = KeyFactory.createKey("Feedbacks",
					curLecture.getLectureID());
			Entity feedback = new Entity("feedback", id);
			feedback.setProperty("user", curUser.getName());
			feedback.setProperty("question1", q1);
			feedback.setProperty("question2", q2);
			feedback.setProperty("question3", q3);

			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();
			datastore.put(feedback);
			Window.alert("Feedback gespeichert!");
		}
		else{
			Window.alert("Du hast schon ein Feedback zu dieser Lecture abgegeben!");
		}
	}

	public boolean feedbackExists(Lecture curLecture, Student curUser) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Key id = KeyFactory.createKey("Feedbacks", curLecture.getLectureID());
		Query query = new Query("Feedback", id).addFilter("user",
				Query.FilterOperator.EQUAL, curUser.getName());
		if (query != null)
			return true;
		else
			return false;
	}
}
